package Server.impl;

import BaseQuery.BaseQuery;
import Bean.Order;
import Dao.IOrderDao;
import Dao.impl.OrderDao;
import Server.IOrderServe;
import com.alibaba.druid.util.StringUtils;
import vo.PageBean;
import vo.ResultBean;

import java.util.ArrayList;
import java.util.List;

public class OrderServe implements IOrderServe {
	private IOrderDao orderDao;
	public OrderServe() {
		orderDao=new OrderDao();
	}
	@Override
	public ResultBean add(Order order) throws Exception {
		if(StringUtils.isEmpty(order.getUserId())||order==null) {
			return ResultBean.ERROR("params is null");
		}
		int count=orderDao.add(order);
		return count>0?ResultBean.SUCCESS():ResultBean.ERROR("add order is fail");
	}

	@Override
	public ResultBean update(Order order) throws Exception {
		if(order==null|| StringUtils.isEmpty(order.getUserId()) || order.getOrderId() == null) {
			return ResultBean.ERROR("params is null");
		}
		int count=orderDao.update(order);
		System.out.println("count:" + count);
		return count>0?ResultBean.SUCCESS():ResultBean.ERROR("update order is fail");
	}

	@Override
	public ResultBean delete(Integer id) throws Exception {
		if(id==null) {
			return ResultBean.ERROR("params is null");
		}
		int count=orderDao.delete(id);
		return count>0?ResultBean.SUCCESS():ResultBean.ERROR("delete order is fail");
	}

	@Override
	public ResultBean getById(Integer id) throws Exception {
		if(id==null) {
			return ResultBean.ERROR("params is null");
		}
		Order order=orderDao.getById(id);
		return order!=null?ResultBean.SUCCESS(order):ResultBean.ERROR("table is not contains this Id");
	}

	@Override
	public ResultBean getAll() throws Exception {
		List<Order> list=orderDao.getAll();
		return ResultBean.SUCCESS(list);
	}

	@Override
	public ResultBean getByPage(BaseQuery baseQuery) throws Exception {
		PageBean<Order> pageBean=new PageBean<>();
		int count=orderDao.getCount(baseQuery);
		pageBean.setTotalRows(count);
		if(count%baseQuery.getPageCount()==0) {
			pageBean.setTotalPages(count/baseQuery.getPageCount());
		} else {
			pageBean.setTotalPages(count%baseQuery.getPageCount()+1);
		}
		List<Order> list=orderDao.getByPage(baseQuery);
		pageBean.setData(list);
		return ResultBean.SUCCESS(pageBean);
	}
	@Override
	public ResultBean batchDel(List<Integer> ids) throws Exception {
		if (ids == null || ids.size() == 0) {
			return ResultBean.ERROR("params is null");
		}
		for (Integer id : ids) {
			orderDao.delete(id);
		}
		return ResultBean.SUCCESS();
	}
}
